from typing import Any

from fastapi import Depends
from sqlalchemy.orm import Session

from app.api.system.schemas import permission_schema
from app.api.system.crud.permission_crud import crud_permission
from app.db.database import get_db
from app.models.system import Users
from app.utils import security
from app.utils.custom_response import success_response
from fastapi import APIRouter, Query, Body, Path

router = APIRouter()


@router.post("/create_permission", summary="新增权限", response_model=permission_schema.CreatePermission, name='新增权限')
async def create_permission(
    *,
    db: Session = Depends(get_db),
    permission_info: permission_schema.CreatePermission,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    permission = crud_permission.create(db, data=permission_info)
    only = ('id', 'name', 'url', 'group', 'method')
    return success_response(data=permission.to_dict(only=only))


@router.post("/delete_permission", summary="删除权限", response_model=permission_schema.CreatePermission, name='删除权限')
async def delete_permission(
    *,
    db: Session = Depends(get_db),
    req_data: permission_schema.DeletePermission,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    crud_permission.delete(db, req_body=req_data)

    return success_response(data={})


@router.post("/update_permission/{permission_id}", summary="更新权限", response_model=permission_schema.CreatePermission, name='更新权限')
async def update_permission(
    *,
    db: Session = Depends(get_db),
    permission_id,
    permission_info: permission_schema.UpdatePermission,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    instance = crud_permission.get_object(db, permission_id)
    instance = crud_permission.update(db, instance=instance, data=permission_info)
    only = ('id', 'name', 'url', 'group', 'method')
    return success_response(data=instance.to_dict(only=only))


@router.get("/get_permission_list", summary="获取权限列表", response_model=permission_schema.Permission, name='获取权限列表')
async def get_permission_list(
    *,
    db: Session = Depends(get_db),
    page: int = Query(1, description='页码', ge=1),
    page_size: int = Query(10, description='页面大小', le=50, ge=1),
    search_info: str = Query(None, description='搜索内容'),
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    queryset, total = crud_permission.get_page_queryset(db, page=page, page_size=page_size)
    only = ('id', 'name', 'url', 'group', 'method')
    items = crud_permission.serializer(queryset, only=only)
    resp = {
        "items": items,
        'total': total
    }
    return success_response(data=resp)
